<?php

namespace controller;

/**
 * Description of Users
 *
 * @author Damian
 */
class Users extends Controller {

    public function __construct($options = array()) {
        if (\library\RequestMethods::get("shop")) {
            $this->defaultLayout = "layout/shop";
        }
        parent::__construct($options);
        if ($this->shop) {
            
        }
    }

    public function register() {
        $region = new \model\TblRegion();
        $region->getColumns();
        $session = \library\Registry::get("session");
        $view = $this->getActionView();
        if ($this->shop) {//register as Customer - using shop (not default layout)
            $layoutView = $this->getLayoutView();
            $layoutView->set("paneltitle", "rejestracja w sklepie " . $this->shop->Name);
            $view->set("shop", $this->shop->Name);
            $basket = ($session->get("basket")) ? $session->get("basket") : new \library\Basket();
            $layoutView->set("basket", $basket);
        }
        $personTmp = new \model\TblPerson();
        $personTmp->getColumns();
        $view->set("person", $personTmp);
        /* @var $session \library\Session\Server */
        if (\library\RequestMethods::post("inputRegisterSubmit") != null) {
            $register = "inputRegister";
            $date = new \DateTime();
            $session->set("register", array(
                "Name" => \library\RequestMethods::post($register . "Name"),
                "Surname" => \library\RequestMethods::post($register . "Surname"),
                "Email" => \library\RequestMethods::post($register . "Email"),
                "PhoneNumber" => \library\RequestMethods::post($register . "Phone"),
                "Password" => \library\RequestMethods::post($register . "Password"),
                "PasswordRepeat" => \library\RequestMethods::post($register . "PasswordRepeat"),
                "IsAdmin" => false,
                "RegisterDate" => $date->format('Y-m-d H:i:s')
            ));
            $person = new \model\TblPerson($session->get("register"));
            if (!$person->validate()) {
                $view->erase("person");
                $view->set("person", $person);
                $view->set("errors", $person->getErrors());
            } else {
                try {
                    $id = $person->save();
                    //save person address
                    $postCodeCriteria = new \model\Criteria();
                    $postCodeCriteria->from(\model\TblPostCode::getModel()->getTable())
                            ->where(\model\TblPostCode::CODE, "=", \library\RequestMethods::post($register . "PostCode"))
                            ->where(\model\TblPostCode::STREET_ID, "=", \library\RequestMethods::post($register . "Street", 1), false, " and ");
                    if (\library\RequestMethods::post($register . "City")) {
                        $postCodeCriteria->where(\model\TblPostCode::CITY_ID, "=", \library\RequestMethods::post($register . "City"), false, " and ");
                    }
                    $postCode = \model\TblPostCode::getModel()->first($postCodeCriteria);
                    if ($postCode && \library\RequestMethods::post($register . "Number")) {
                        $city = (\library\RequestMethods::post($register . "City")) ? \library\RequestMethods::post($register . "City") : $postCode->CityID;
                        $adress = new \model\TblAdress([
                            \model\TblAdress::POST_CODE_ID => $postCode,
                            \model\TblAdress::NUMBER => \library\RequestMethods::post($register . "Number"),
                            \model\TblAdress::DEFAULT_ADRESS => 1,
                            \model\TblAdress::PERSON_ID => $id,
                            \model\TblAdress::STREET_ID => \library\RequestMethods::post($register . "Street", 1),
                            \model\TblAdress::CITY_ID => $city
                        ]);
                        $adress->save();
                    }
                    //shop does not exists - we can register as seller and in the next step create shop
                    if (!$this->shop) {
                        $seller = new \model\TblSeller(
                                [\model\TblSeller::PERSON_ID => $id,
                            \model\TblSeller::CREATED_SHOP => 0]
                        );
                        $seller->save();
                         $this->redirect("ShopAdmin");
                    } else {//register as customer
                        $shopCriteria = new \model\Criteria();
                        $shopCriteria->from(\model\TblShop::getModel()->getTable())->where(\model\TblShop::URL, "=", $this->shop->URL);
                        $shop = \model\TblShop::getModel()->first($shopCriteria);
                        $customer = new \model\TblCustomer([
                            \model\TblCustomer::PERSON_ID => $id,
                            \model\TblCustomer::SHOP_ID => $shop->ShopID
                        ]);
                        $customer->save();
                        $this->redirect($this->shop->URL);
                       
                    }
                    $session->erase("register");
                    $session->set("login", $person);
                    $view->set("success", "Rejestracja przebiegła pomyślnie");
                    $view->erase("person");
                    $view->set("person", $person);
                    $view->erase("errors");
                    $view->set("errors", $person->getErrors());
                } catch (\model\exceptions\ExceptionSQLQUery $ex) {
                    if ($ex->getCode() == 1062) {
                        $view->set("emailError", "Podany adres Email jest już zarejestrowany");
                    } else {
                        throw $ex;
                    }
                } catch (\Exception $e) {
                    var_dump($e);
                }
            }
        }
        $this->render();
    }
    public function RemindPassword(){        
        $view = $this->getActionView();
         $layoutView = $this->getLayoutView();
         $layoutView->set("paneltitle", "Zmiana hasła");
         if (\library\RequestMethods::post("inputLoginEmail")){
            $usersCriteria = new \model\Criteria();
            $usersCriteria->from(\model\TblPerson::getModel()->getTable())
                    ->where(\model\TblPerson::EMAIL, "=", \library\RequestMethods::post("inputLoginEmail"));
            $user = \model\TblPerson::getModel()->first($usersCriteria);
            if (!$user){
                $error="Podany adres email (".\library\RequestMethods::post("inputLoginEmail").") nie został znaleziony w bazie danych. Hasło nie zostanie zmienione";
                $view->set("error",$error);
            }
            else {
                $password = $user->generatePassword();
                $hashBase=time().$user->Name.time().$user->Email.time().$user->RegisterDate.time();
                $hash = substr(base64_encode(\library\StringMethods::encrypt($hashBase)),rand(1,10),rand(30,35));
                $date = new \DateTime();
                $LogChange = new \model\TblLogChangePassword([
                \model\TblLogChangePassword::CHANGE_DATE=>$date->format("Y-m-d H:i:s"),
                \model\TblLogChangePassword::HASH=>$hash,
                \model\TblLogChangePassword::PERSON_ID=>  $user->PersonID,
                \model\TblLogChangePassword::CHANGED =>0,
                \model\TblLogChangePassword::PASSWORD_HASH =>  password_hash($password, PASSWORD_DEFAULT)
                ]);
                $LogChange->save();
                $mailBody = "Witaj ".$user->Name." ".$user->Surname;
                $mailBody = "Ktoś podał ten adres email w celu zmiany hasła w sklepie internetowym ".$this->shop->Name."<br>";
                $url = "http://localhost:8080/".  $this->shop->URL."/users/ChangePassword?hash=".urlencode($hash);
                $mailBody."<h2>Witaj ".$user->Name." ".$user->Surname."</h2>";
                $mailBody.="Aby zmienić hasło kliknij w odnośnik poniżej <br>" . $url;
                $mailBody.="<br>Odnośnik jest ważny przez 24 godziny, po tym czasie zmiana hasła nie będzie możliwa <br/>";
                $mailBody.="hasło wygenerowane przez system: <b>".$password."</b>";
                try {
                    $mail = new \library\Mail();
                    $mail->AddAddress($user->Email, $user->Name." ".$user->Surname);
                    $mail->sendEmail("zmiana hasła w sklepie ".$this->shop->Name, $mailBody, "sprzedawca");
                    $view->set("chceckMail", "Sprawdź pocztę email, i kliknij w odnośnik aby zmienić hasło. Sprawdź folder SPAM");                    
                } catch (\library\exceptions\MailException $e) {
                     $view->set("error", $e->getMessage());
                }
            }
        }
        if (\library\RequestMethods::get("hash")){
            $criteria = new \model\Criteria();
            $criteria->from(\model\TblLogChangePassword::getModel()->getTable())
                    ->where(\model\TblLogChangePassword::HASH, "=", \library\RequestMethods::get("hash"))
                    ->where(\model\TblLogChangePassword::CHANGED, "=", 0, false, " and ")
                     ->where("hour(timediff(now()," . \model\TblLogChangePassword::CHANGE_DATE. "))", "<", 24, false, " and ", false)
                    ->order(\model\TblLogChangePassword::CHANGE_DATE," desc ")
                    ->limit(1);
            $newPassword=  \model\TblLogChangePassword::getModel()->all($criteria);
            if (sizeof($newPassword)==0){
                $view->set("error", "Hash został już wykorzystany, stracił ważność lub jest niepoprawny");
                 $this->render();
                 return;
            }
            $person = \model\TblPerson::getModel()->getByPrimaryKey($newPassword[0]->PersonID);
            $person->Password = $newPassword[0]->PasswordHash;
            $newPassword[0]->Changed=1;
            $newPassword[0]->save();
            $person->save();
            $view->set("chceckMail", "Hasło zostało zmienione. Możesz się zalogować nowymi danymi");   
        }
         $this->render();
    }

    public function Login() {
        $session = \library\Registry::get("session");
        $view = $this->getActionView();
        $errors = array();
        try {
            //sprawdzenie czy zalogowany i zapisanie informacji czy sprzedawca czy klient
            $login = \library\RequestMethods::post("inputLoginEmail");
            $password = \library\RequestMethods::post("inputLoginPassword");
            if ($login && $password) {
                $personCriteria = new \model\Criteria();
                $personCriteria->from(\model\TblPerson::getModel()->getTable())->where(\model\TblPerson::EMAIL, "=", $login);
                $person = \model\TblPerson::getModel()->first($personCriteria);
                $date = new \DateTime();
                $LogLogin = new \model\TblLogLogin([
                \model\TblLogLogin::IP =>  $this->getRealIpAddr(),
                \model\TblLogLogin::LOGIN_DATE => $date->format('Y-m-d H:i:s')
                ]);
                if (!$person){
                    $errors["Email"][] = "Podany użytkownik nie istnieje";
                    $view->set("errors", $errors);
                    $this->render();
                }else if (!password_verify($password, $person->Password)) {
                    $session->set("login", $person);
                     $shop = $session->get("shop");
                    $LogLogin->PersonID=$person->PersonID;
                    $LogLogin->Correct=0;
                    $LogLogin->ShopID=  $shop->ShopID;
                    $LogLogin->save();
                    $errors["Password"][] = "Podane hasło jest niepoprawne";
                    $view->set("errors", $errors);
                    $this->render();
                } else {//logowanie poprawne  
                    $session->set("login", $person);
                     $LogLogin->PersonID=$person->PersonID;
                    $LogLogin->Correct=1;
                    $shop = $session->get("shop");
                    $LogLogin->ShopID=  $shop->ShopID;
                    $LogLogin->save();
                    //sprawdzenie czy sprzedawca
                    try {
                        $sellerCriteria = new \model\Criteria();
                        $sellerCriteria->from(\model\TblSeller::getModel()->getTable())->where(\model\TblSeller::PERSON_ID, "=", $person->PersonID);
                        $seller = \model\TblSeller::getModel()->first($sellerCriteria);
                        if (!$seller) {
                            // $this->redirect($shop->URL);
                            $customerCriteria = new \model\Criteria();
                            $customerCriteria->from(\model\TblCustomer::getModel()->getTable())->where(\model\TblSeller::PERSON_ID, "=", $person->PersonID);
                            $customer = \model\TblCustomer::getModel()->first($customerCriteria);
                            $session->set("customer", $customer);
                            $shopCriteria = new \model\Criteria();
                            $shopCriteria->from(\model\TblShop::getModel()->getTable())->where(\model\TblShop::ID, "=", $customer->ShopID);
                            $shop = \model\TblShop::getModel()->first($shopCriteria);
                            if ($session->get("last_url")){
                                $url = $session->get("last_url");
                                $session->erase("last_url");
                                $this->redirect($url, false);
                            }
                            $this->redirect($shop->URL);
                        } else if ($seller->CreatedShop == 1 || $seller->CreatedShop==2) {
                            $session->set("seller", $seller);
                            $shopCriteria = new \model\Criteria();
                            $shopCriteria->from(\model\TblShop::getModel()->getTable())->where(\model\TblShop::SELLER_ID, "=", $seller->SellerID);
                            $shop = \model\TblShop::getModel()->first($shopCriteria);
                            if ($session->get("last_url")){
                                $url = $session->get("last_url");
                                $session->erase("last_url");
                                $this->redirect($url, false);
                            }
                            $this->redirect($shop->URL . "/seller");
                        } else {
                            $session->set("seller", $seller);
                            $this->redirect("shopadmin");
                        }
                    } catch (\model\exceptions\NoDataException $e) {
                        
                    }
                    $customerCriteria = new \model\Criteria();
                    $customerCriteria->from(\model\TblCustomer::getModel()->getTable())->where(\model\TblCustomer::PERSON_ID, "=", $person->PersonID);
                    $customer = \model\TblCustomer::getModel()->first($customerCriteria);
                    if ($customer) {
                        $session->set("customer", $customer);
                        $shop = \model\TblShop::getModel()->getByPrimaryKey($customer->ShopID);
                        $this->redirect($shop->URL . "/shop");
                    }
                }
            } else {
                if ($this->shop) {
                    $layoutView = $this->getLayoutView();
                    $layoutView->set("paneltitle", "Zaloguj się do sklepu " . $this->shop->Name);
                    $view->set("shop", $this->shop->Name);
                    $basket = ($session->get("basket")) ? $session->get("basket") : new \library\Basket();
                    $layoutView->set("basket", $basket);
                }
                $this->render();
            }
        } catch (\model\exceptions\ExceptionSQLQUery $exc) {
            //var_dump($exc);
        }
    }

    public function Logout() {
        $session = \library\Registry::get("session");
        $session->erase("login");
        $session->erase("login");
        $session->erase("seller");
        $session->erase("customer");
        $session->erase("categoryID");
        $this->redirect($this->shop->URL . "/shop");
        $this->render();
    }
}
